/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2022 kindeditor.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://kindeditor.net/
* @licence http://kindeditor.net/license.php
*******************************************************************************/
(function (K) {
    function h5upload(options) {
        this.init(options);
    }
    K.extend(h5upload, {
        init: function (options) {
            var self = this;
            options.afterError = options.afterError || function (str) {
                alert(str);
            };
            self.options = options;
            self.progressbars = {};
            self.div = K(options.container).html([
                '<div class="ke-swfupload">',
                '<div class="ke-swfupload-top">',
                '<div class="ke-upload-area" style="width:80px;float:left;">',
                '<span class="ke-button-common ke-button-outer"><input type="button" class="ke-button-common ke-button" value="' + options.buttonText + '"></span>',
                '<input type="file" id="multifile" name="multifile" multiple="" class="ke-upload-file" tabindex="-1" />',
                '</div>',
                '<div class="ke-inline-block ke-swfupload-desc">' + options.uploadDesc + '</div>',
                '<span class="ke-button-common ke-button-outer ke-swfupload-startupload">',
                '<input type="button" class="ke-button-common ke-button" value="' + options.startButtonValue + '" />',
                '</span>',
                '</div>',
                '<div class="ke-swfupload-body"></div>',
                '</div>'
            ].join(''));
            self.bodyDiv = K('.ke-swfupload-body', self.div);
            function showError(itemDiv, msg) {
                K('.ke-status > div', itemDiv).hide();
                K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg));
            }

            /*点击开始上传*/
            K('.ke-swfupload-startupload', self.div).click(function () {
                /*防止重复点击*/
                if (!options.enableupload) {
                    return;
                }
                options.enableupload = false;
                for (var i = 0; i < options.file_arr.length; i++) {
                    let file = options.file_arr[i];
                    /*过滤已上传的*/
                    if (file.filestatus == 0) {
                        let form = new FormData(); // FormData 对象
                        form.append(options.filePostName, options.file_arr[i]); // 文件对象
                        let sendAjax = new XMLHttpRequest();
                        sendAjax.open("post", options.uploadUrl, true);
                        sendAjax.onload = function (e) {
                            let itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
                            let data = {};
                            try {
                                data = K.json(e.target.responseText);
                            } catch (ex) {
                                self.options.afterError.call(this, '<!doctype html><html>' + e.target.responseText + '</html>');
                            }
                            if (data.error !== 0) {
                                showError(itemDiv, K.DEBUG ? data.message : self.options.errorMessage);
                                return;
                            }
                            file.url = data.url;
                            K('.ke-img', itemDiv).attr('src', file.url).attr('data-status', 1).data('data', data);
                            K('.ke-status > div', itemDiv).hide();

                            options.file_arr.forEach(function (item, idx) {
                                if (item.id == file.id) {
                                    options.file_arr[idx].filestatus = 1;//标记文件已上传
                                }
                            });
                        }; //请求完成
                        sendAjax.onerror = function (e) {
                            let itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
                            showError(itemDiv, self.options.errorMessage);
                        }; //请求失败
                        sendAjax.upload.onprogress = function (e) {
                            let total = e.total;
                            let loaded = e.loaded;
                            let percent = Math.round(loaded * 100 / total);
                            let progressbar = self.progressbars[file.id];
                            progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px');
                            progressbar.percent.html(percent + '%');
                        };//【上传进度调用方法实现】
                        sendAjax.upload.onloadstart = function () {//上传开始执行方法
                            let itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv);
                            K('.ke-status > div', itemDiv).hide();
                            K('.ke-progressbar', itemDiv).show();
                        };
                        sendAjax.send(form); //开始上传，发送form数据
                    }
                }

            });
            /*选择图片时间*/
            K("#multifile", self.div).change(function () {
                if (!options.filecount) {
                    options.filecount = 0;
                }
                if (!options.file_arr) {
                    options.file_arr = new Array();
                }

                var f = this.files;
                for (var i = 0; i < f.length; i++) {
                    let ext = "*" + f[i].name.toLowerCase().substr(f[i].name.lastIndexOf('.'));
                    if (options.fileTypes.indexOf(ext) == -1) {
                        alert(f[i].name + "文件格式不支持");
                    } else if (parseFloat(f[i].size / 1024 / 1024) >= 5) {
                        alert(f[i].name + "文件大小超过5M，已忽略")
                    } else {
                        options.filecount++;
                        f[i].url = options.fileIconUrl;
                        f[i].id = "file_" + options.filecount;
                        f[i].filestatus = 0;

                        self.appendFile(f[i]);
                        options.file_arr.push(f[i]);
                    }
                }
                /*记录未上传文件数量*/
                let temp = 0;
                options.file_arr.forEach(function (item) {
                    if (item.filestatus == 0) {
                        temp++;
                    }
                });
                if (temp > 0) {
                    options.enableupload = true;/*启用上传按钮*/
                } else {
                    options.enableupload = false;/*禁用上传按钮*/
                }
            });
        },
        getUrlList: function () {
            var list = [];
            K('.ke-img', self.bodyDiv).each(function () {
                var img = K(this);
                var status = img.attr('data-status');
                if (status == 1) {
                    list.push(img.data('data'));
                }
            });
            return list;
        },
        removeFile: function (fileId) {
            var self = this;
            var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv);
            K('.ke-photo', itemDiv).unbind();
            K('.ke-delete', itemDiv).unbind();
            itemDiv.remove();

            let arr = new Array();
            self.options.file_arr.forEach(function (item, i) {
                if (item.id != fileId) {
                    arr.push(item);
                }
            });
            self.options.file_arr = arr;
        },
        removeFiles: function () {
            var self = this;
            K('.ke-item', self.bodyDiv).each(function () {
                self.removeFile(K(this).attr('data-id'));
            });
            if (self.options.file_arr) {
                self.options.file_arr.splice(0, self.options.file_arr.length);
            }
        },
        appendFile: function (file) {
            var self = this;
            var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>');
            self.bodyDiv.append(itemDiv);
            var photoDiv = K('<div class="ke-inline-block ke-photo"></div>').mouseover(function (e) {
                K(this).addClass('ke-on');
            }).mouseout(function (e) {
                K(this).removeClass('ke-on');
            });
            itemDiv.append(photoDiv);
            var img = K('<img src="' + file.url + '" class="ke-img" data-status="' + file.filestatus + '" width="80" height="80" alt="' + file.name + '" />');
            photoDiv.append(img);
            K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function () {
                self.removeFile(file.id);
            });
            var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv);
            K(['<div class="ke-progressbar">',
                '<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>',
                '<div class="ke-progressbar-percent">0%</div></div>'].join('')).hide().appendTo(statusDiv);
            K('<div class="ke-message">' + self.options.pendingMessage + '</div>').appendTo(statusDiv);
            itemDiv.append('<div class="ke-name">' + file.name + '</div>');
            self.progressbars[file.id] = {
                bar: K('.ke-progressbar-bar-inner', photoDiv),
                percent: K('.ke-progressbar-percent', photoDiv)
            };
        },
        remove: function () {
            this.removeFiles();
            this.div.html('');
        }
    });
    K.H5Upload = function (options) {
        return new h5upload(options);
    };
})(KindEditor);

KindEditor.plugin('multiimage', function (K) {
    var self = this, name = 'multiimage',
        formatUploadUrl = K.undef(self.formatUploadUrl, true),
        uploadJson = K.undef(self.uploadJson, self.basePath + 'asp.net/upload_json.ashx'),
        imgPath = self.pluginsPath + 'multiimage/images/',
        imageSizeLimit = K.undef(self.imageSizeLimit, '5MB'),
        imageUploadLimit = K.undef(self.imageUploadLimit, 20),
        filePostName = K.undef(self.filePostName, 'imgFile'),
        lang = self.lang(name + '.');

    self.plugin.multiImageDialog = function (options) {
        var clickFn = options.clickFn, uploadDesc = K.tmpl(lang.uploadDesc, { uploadLimit: imageUploadLimit, sizeLimit: imageSizeLimit });
        var html = [
            '<div style="padding:20px;">',
            '<div class="swfupload">',
            '</div>',
            '</div>'
        ].join('');

        var dialog = self.createDialog({
            name: name,
            width: Math.min(document.body.clientWidth, 650),
            height: 510,
            title: self.lang(name),
            body: html,
            /*全部插入*/
            previewBtn: {
                name: lang.insertAll,
                click: function (e) {
                    clickFn.call(self, H5Upload.getUrlList());
                }
            },
            /*全部清空*/
            yesBtn: {
                name: lang.clearAll,
                click: function (e) {
                    H5Upload.removeFiles();
                }
            },
            /*取消按钮*/
            beforeRemove: function () {
                if (!K.IE || K.V <= 8) {
                    H5Upload.remove();
                }
            }
        }),
            div = dialog.div;
        var H5Upload = K.H5Upload({
            container: K('.swfupload', div),
            buttonText: (self.langType == 'zh-CN' ? '浏览图片' : 'Browser'),
            buttonWidth: self.langType == 'zh-CN' ? 72 : 88,
            buttonHeight: 23,
            fileIconUrl: imgPath + 'image.png',
            uploadDesc: uploadDesc,
            startButtonValue: lang.startUpload,
            uploadUrl: K.addParam(uploadJson, 'dir=image'),
            filePostName: filePostName,
            fileTypes: '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
            fileUploadLimit: imageUploadLimit,
            fileSizeLimit: imageSizeLimit,
            unknownError: lang.unknownError,
            pendingMessage: lang.pending,
            errorMessage: lang.uploadError,
            afterError: function (html) {
                self.errorDialog(html);
            }
        });
        return dialog;
    };

    self.clickToolbar(name, function () {
        self.plugin.multiImageDialog({
            clickFn: function (urlList) {
                if (urlList.length === 0) {
                    return;
                }
                K.each(urlList, function (i, data) {
                    if (self.afterUpload) {
                        self.afterUpload.call(self, data.url, data, 'multiimage');
                    }
                    self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align);
                });
                setTimeout(function () {
                    self.hideDialog().focus();
                }, 0);
            }
        });
    });
});